const { ref, onMounted } = Vue;

// 视频信息管理模块
const videoModule = () => {
    const video = ref({});
    const tags = ref([]);
    const comments = ref([]);
    const current_comment = ref('');
    const video_user_info = ref({});
    const comment_user_info = ref([]);
    const comment_user_info_map = ref([]);
    const comment_block = ref([]);
    const current_comment_block_index = ref(0);
    const similar_video = ref([]);
    const user_video_relation = ref({
        is_liked: '0',
        dislike: '0',
        favorite: '0',
        grade: '0.0',
    });

    const get_user_video_relation = () => {
        axios.get("/video/getVideoRelation?video_id=" + video.value.video_id)
            .then((response) => {
                user_video_relation.value = response.data;
            })
            .catch((error) => {
                console.error("获取用户和视频的关系失败", error);
            });
    };

    const user_video_relation_str = () => {
        return `is_liked=${user_video_relation.value.is_liked}&dislike=${user_video_relation.value.dislike}&favorite=${user_video_relation.value.favorite}&grade=${user_video_relation.value.grade}`;
    };

    const update_user_video_relation = (type) => {
        if (type !== 'grade') {
            user_video_relation.value[type] = user_video_relation.value[type] === '0' ? '1' : '0';
        } else {
            user_video_relation.value.grade = grade;
        }
        axios.post(`/video/updateVideoRelation?video_id=${video.value.video_id}&${user_video_relation_str()}`)
            .then(() => {
                console.log("更新用户和视频的关系成功");
                get_video();
            })
            .catch((error) => {
                console.error("更新用户和视频的关系失败", error);
            });
    };

    const get_param = (name) => {
        return decodeURIComponent((new RegExp(`[?|&]${name}=([^&;]+?)(&|#|;|$)`).exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null;
    };

    const get_similar_video = () => {
        axios.get(`/video/getVideoOfType?type_id=${video.value.video_type_id}&number=6`)
            .then((response) => {
                similar_video.value = response.data.filter((item) => item.video_id !== video.value.video_id);
            })
            .catch((error) => {
                console.error("获取相似视频失败", error);
            });
    };

    const get_video = () => {
        const id = get_param("id");
        axios.get(`/video/${id}`)
            .then((result) => {
                video.value = result.data;
                get_video_user_info();
                get_similar_video();
                return Promise.all([get_comments(), get_comment_user_info()]);
            })
            .then(() => {
                map_comment_user_info();
                get_user_video_relation();
            })
            .catch((error) => {
                console.error("获取视频信息失败", error);
            });

        axios.get(`/tag/${id}`)
            .then((data) => {
                tags.value = data.status === 204 ? [] : data.data;
            })
            .catch((error) => {
                console.error("获取标签信息失败", error);
            });
    };

    const get_video_user_info = () => {
        axios.get(`/user/getVideoUserInfo?id=${video.value.video_id}`)
            .then((response) => {
                video_user_info.value = response.data;
            })
            .catch((error) => {
                console.error("获取视频用户信息失败", error);
            });
    };

    const get_comments = () => {
        return axios.get(`/comment/getComment?id=${video.value.video_id}`)
            .then((response) => {
                comments.value = response.data;
            })
            .catch((error) => {
                console.error("获取评论失败", error);
            });
    };

    const send_comment = () => {
        if (current_comment.value === '') {
            alert("评论不能为空");
            return;
        }
        axios.post(`/comment/sendComment?id=${video.value.video_id}`, { comment: current_comment.value })
            .then((response) => {
                if (response.status === 200) {
                    current_comment.value = '';
                    return Promise.all([get_comments(), get_comment_user_info()]);
                } else {
                    alert("发送评论失败");
                    current_comment.value = '';
                }
            })
            .then(() => {
                map_comment_user_info();
                console.log("发送评论成功, current_comment : ", current_comment.value);
            })
            .catch((error) => {
                console.error("发送评论失败", error);
            });
    };

    const get_comment_user_info = () => {
        return axios.get(`/user/getCommentUserInfo?id=${video.value.video_id}`)
            .then((response) => {
                comment_user_info.value = response.data;
            })
            .catch((error) => {
                console.error("获取评论用户信息失败", error);
            });
    };

    const map_comment_user_info = () => {
        comment_user_info_map.value = comments.value.map(comment => {
            const user_info = comment_user_info.value.find(item => item.uid === comment.sender_uid);
            return { comment, user_info };
        });

        comments.value = [];
        comment_user_info.value = [];
        comment_block.value = [];

        for (let i = 0; i < comment_user_info_map.value.length; i += 5) {
            comment_block.value.push(comment_user_info_map.value.slice(i, i + 5));
        }

        comment_user_info_map.value = [];
    };

    const prevBlock = () => {
        if (current_comment_block_index.value > 0) {
            current_comment_block_index.value--;
        } else {
            alert("已经是第一页了");
        }
    };

    const nextBlock = () => {
        if (current_comment_block_index.value < comment_block.value.length - 1) {
            current_comment_block_index.value++;
        } else {
            alert("已经是最后一页了");
        }
    };

    return {
        video, tags, get_video, current_comment, send_comment,
        video_user_info, similar_video, comment_block, current_comment_block_index,
        prevBlock, nextBlock, user_video_relation, update_user_video_relation
    };
};

// 用户信息管理模块
const userModule = () => {
    const userinfo = ref({});

    const getUserInfo = async () => {
        try {
            const res = await axios.get('/user/getUserInfo');
            userinfo.value = res.data;
        } catch (error) {
            console.error("获取用户信息失败", error);
        }
    };

    return { userinfo, getUserInfo };
};

// 搜索功能模块
const userSearch = () => {
    const searchQuery = ref('');

    const redirectToSearch = () => {
        window.location.href = `/search.html?search=${searchQuery.value}`;
    };

    return { searchQuery, redirectToSearch };
};

const myapp = Vue.createApp({
    setup() {
        const {
            video, tags, get_video, current_comment, send_comment,
            video_user_info, similar_video, comment_block, user_video_relation,
            update_user_video_relation, current_comment_block_index, prevBlock, nextBlock
        } = videoModule();

        const { userinfo, getUserInfo } = userModule();
        const { searchQuery, redirectToSearch } = userSearch();

        onMounted(async () => {
            await get_video();
            getUserInfo();
        });

        return {
            userinfo, video, tags, searchQuery, redirectToSearch,
            current_comment, send_comment, video_user_info, similar_video,
            comment_block, current_comment_block_index, prevBlock, nextBlock,
            user_video_relation, update_user_video_relation
        };
    },
}).mount('#myapp');

// 头像点击跳转
document.querySelector('.avatar')?.addEventListener('click', function () {
    window.location.href = 'personal.html';
});